package task3;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConnectionUser implements Runnable{

	private static final Logger LOGGER = Logger.getLogger(ConnectionUser.class.getName());
	
	ConnectionPool pool;
	
	private static int idInitializer = 0;
	private int id = getId();
	
	public ConnectionUser(ConnectionPool pool){
		this.pool = pool;
	}
	
	public void run(){
		
		Random r = new Random();
		
		try {
			Connection connection = null;
			try {
				System.out.println("User " + id + " is trying to take connection");
				connection = pool.checkout();
				System.out.println("User " + id + " has taken the connection");
			} catch (InterruptedException e) {
				System.out.println("User " + id + " didn't take the connection : " + e.getMessage());
				return;
			}
			
			//using connection
			do{
				try {
					connection.prepareStatement(null);
					Thread.sleep(r.nextInt(2000) + 1000);
					connection.close();
				} catch (SQLException e) {
					LOGGER.log(Level.SEVERE, e.getMessage());
				}
			} while(r.nextInt(10) < 4);
			
			if(r.nextInt(5) < 2){
				pool.checkin(connection);
				System.out.println("User " + id + " has returned the connection");
			} else{
				System.out.println("User " + id + " forgot to return the connection");
			}
		} catch (InterruptedException e) {
			LOGGER.log(Level.SEVERE, e.getMessage());
		}
	}

	private static int getId(){
		return ++idInitializer;
	}
	
}
